import { BaseResponse } from '@/common/BaseResponse';
import { DictionaryWords } from '@/entity/dictionary-words.entity';
import { Dictionary } from '@/entity/dictionary.entity';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { PageParamDto } from './dto/page-param.dto';

@Injectable()
export class WordService {
  constructor(
    @InjectRepository(Dictionary)
    private readonly dictionaryRepository: Repository<Dictionary>,
    @InjectRepository(DictionaryWords)
    private readonly dictionaryWordsRepository: Repository<DictionaryWords>,
  ) {}

  async wordListSelect(pageParamDto: PageParamDto) {
    const qb =
      this.dictionaryWordsRepository.createQueryBuilder('dictionaryWords');
    let result = qb;

    if (pageParamDto.dictionaryId) {
      result = qb.andWhere(`dictionaryWords.dictionary_id = :dictionaryWords`, {
        dictionaryWords: pageParamDto.dictionaryId,
      });
    }

    if (pageParamDto.content) {
      result = qb.andWhere(
        `dictionaryWords.word_content like '%${pageParamDto.content}%'`,
      );
    }

    result
      .leftJoinAndMapOne(
        'dictionaryWords.dictionaryInfo',
        Dictionary,
        'dictionary',
        'dictionary.id = dictionaryWords.dictionaryId',
      )
      .limit(pageParamDto.size)
      .offset((pageParamDto.page - 1) * pageParamDto.size);
    const total = await result.getCount();
    const list = await result.getMany();

    return BaseResponse.toSuccesJustData({
      page: Number(pageParamDto.page),
      list,
      size: Number(pageParamDto.size),
      total,
    });
  }

  deleteWord(id: number) {
    return this.dictionaryWordsRepository.delete(id);
  }
}
